package com.qiyun.framework.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * sp配置数据保存(同步)
 * Created by Tiger on 2016/1/12.
 */
public class SharePreHelper {
    private static SharedPreferences mSharedPreferences;
    private static boolean mIsInited = false;
    private static SharedPreferences.Editor mEditor;

    public SharePreHelper() {
    }

    public static void init(Context context) {
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        mEditor = mSharedPreferences.edit();
        mIsInited = true;
    }

    private static SharedPreferences getSharedPreferences() {
        if(mIsInited) {
            return mSharedPreferences;
        } else {
            throw new NullPointerException("do init(Context context) before work");
        }
    }

    private static SharedPreferences.Editor getEditor() {
        if(mIsInited) {
            return mEditor;
        } else {
            throw new NullPointerException("do init(Context context) before work");
        }
    }

    public static boolean contains(String key) {
        return getSharedPreferences().contains(key);
    }

    public static int getInt(String key, int def) {
        return getSharedPreferences().getInt(key, def);
    }

    public static long getLong(String key, long def) {
        return getSharedPreferences().getLong(key, def);
    }

    public static String getString(String key, String def) {
        return getSharedPreferences().getString(key, def);
    }


    public static boolean getBoolean(String key, boolean def) {
        return getSharedPreferences().getBoolean(key, def);
    }

    public static float getFloat(String key, float def) {
        return getSharedPreferences().getFloat(key, def);
    }

    public static void putInt(String key, int value) {
        getEditor().putInt(key, value);
        getEditor().commit();
    }

    public static void putLong(String key, long value) {
        getEditor().putLong(key, value);
        getEditor().commit();
    }

    public static void putBoolean(String key, boolean value) {
        getEditor().putBoolean(key, value);
        getEditor().commit();
    }

    public static void putString(String key, String value) {
        getEditor().putString(key, value);
        getEditor().commit();
    }

    public static void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
        getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
    }

    public static void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
        getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
    }
}
